package com.pan.note.controller;


import com.pan.note.dto.TimeLineNoteDto;
import com.pan.note.service.NoteService;
import com.pan.note.vo.TimeLineNoteVo;
import io.lettuce.core.resource.Delay;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Date;

/**
 * 时间线接口
 */
@Controller
public class TimeLineController {

    /**
     * 自动装配
     */
    @Autowired
    private NoteService NoteService;

    /**
     * 首页接口
     * @return 首页
     */
    @GetMapping("/index")
    public String getIndex(){
        return "TimeLineIndex";
    }

    @GetMapping("/list")
    @ResponseBody
    public TimeLineNoteVo getMsg(@RequestParam Integer page){
        // 获取数据
        return NoteService.getNote(new Date());
    }

    @GetMapping("/listByPage")
    @ResponseBody
    public String getPage(@RequestParam Integer page){
        // 获取数据
        return NoteService.getNoteByPage(page);
    }

    /**
     * 写日记接口
     * @return 写日记界面
     */
    @RequestMapping("/write")
    public String write(){
        return "WriteNoteIndex";
    }

    /**
     * 上传日记接口
     * @return 首页
     */
    @PostMapping("/upload")
    @ResponseBody
    public String upload(@RequestBody TimeLineNoteDto timeLineNoteDto){
         return NoteService.upLoadNote(timeLineNoteDto);
    }

    /**
     * 上传图片
     * @param file
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/upload/img", method = {RequestMethod.POST})
    @ResponseBody
    public Object upload(@RequestParam(value="file",required=false) MultipartFile file, HttpServletRequest request, HttpServletResponse response) throws Exception {
        return NoteService.uploadPic(file,request,response);
    }

    /**
     * 使用流将图片输出
     * @param response
     * @param name
     * @throws IOException
     */
    @GetMapping("/Users/panyi/Documents/TimeLineNoteData/{name}")
    public void getImage(HttpServletResponse response, @PathVariable("name") String name) throws IOException {
        response.setContentType("image/jpeg;charset=utf-8");
        response.setHeader("Content-Disposition", "inline; filename=girls.png");
        ServletOutputStream outputStream = response.getOutputStream();
        outputStream.write(Files.readAllBytes(Paths.get("/Users/panyi/Documents/TimeLineNoteData/").resolve(name)));
        outputStream.flush();
        outputStream.close();
    }
}
